package com.cljh.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.cljh.bean.Admin;
import com.cljh.service.AdminService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * token工具
 */
@Component
public class TokenUtils {

    private static AdminService staticUserService;

    @Resource
    private AdminService adminService;

    @PostConstruct
    public  void setAdminService(){
        staticUserService=adminService;
    }
    /**
     * 生成token
     * @return token字符串
     */
    public static String genToken(String username,String sign){
        String token="";
        token= JWT.create().withAudience(username) // 将 user id 保存到 token 里面 作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //2小时后token过期 hutool工具
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
//        System.out.println(token);
        return token;
    }

    /**
     * 获取当前登录用户的信息
     */
    public static Admin getCurrentUser(){
        Admin admin ;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token=request.getHeader("token");
            if (StrUtil.isNotBlank(token)){
                String s = JWT.decode(token).getAudience().get(0);
                admin= staticUserService.getById(Integer.valueOf(s));
            }else{
                return null;
            }
        }catch (Exception e){
            return null;
        }
        return admin;
    }
}
